import json
from flask import Blueprint, jsonify
from handle.logger import logger
from handle.S2Redis import sync_data_background,render_template,redis_client,socketio
# 创建一个蓝图对象
test = Blueprint('test', __name__)

# 在蓝图对象上注册路由
@test.route('/')
def test_home():
    print('Broadcasting log event...')
    logger.info('info test')
    logger.warning('warning test')
    logger.error('error test')
    socketio.emit('log', {'data': 'Connected to the server!'})
    # print('Broadcast complete.')
    # socketio.emit('log', {'data': 'Hello from server'})
    return jsonify({"message": f"Connected to the server"})

@test.route('/sync_data', methods=['GET'])
def sync_data():
    """
    启动异步数据同步任务。
    """
    try:
        sync_data_background()
        return "Data syncing initiated successfully!", 200
    except Exception as e:
        return f"Error: {str(e)}", 500

@test.route('/log')
def index():
    return render_template('index.html')

@test.route('/show_data', methods=['GET'])
def show_redis_data():
    """
    显示Redis当前所有数据，并格式化输出
    """
    try:
        keys = redis_client.keys('*')
        data = {}

        for key in keys:
            value = redis_client.get(key)

            try:
                value = json.loads(value.decode('utf-8'))
            except json.JSONDecodeError:
                value = value.decode('utf-8')

            data[key.decode()] = value

        # 将数据直接传递到模板
        return render_template('show_data.html', data=data)

    except Exception as e:
        return f"Error: {str(e)}", 500

@test.route('/show_data/<key>', methods=['GET'])
def show_logistics(key):
    value = json.loads(redis_client.get(key).decode('utf-8'))
    print(value)
    return render_template('show_data.html', data=value)
